package com.suning.sawp.service.impl.job;

import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.google.common.base.Charsets;
import com.suning.framework.image.common.FtpEntity;
import com.suning.framework.image.common.FtpUtils;
import com.suning.sawp.intf.dao.CouponRecordDaoService;
import com.suning.sawp.intf.dao.ValidActivityDaoService;
import com.suning.sawp.intf.job.CouponsJobService;
import com.suning.sawp.po.promotion.CouponRecord;
import com.suning.sawp.service.util.DateUtils;

@Service("couponsJobService")
public class CouponsJobServiceImpl implements CouponsJobService {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(CouponsJobServiceImpl.class);
    
    /**
     * 列分隔符
     */
    public static final String COLUMN_SPACE = "|$|";

    /**
     * 行尾符
     */
    public static final String LINE_END = "|@|";

    /**
     * 行分隔符
     */
    public static final String LINE_SPACE = "\n";
    
    @Resource
    ValidActivityDaoService validActivityDaoService;
    
    @Resource
    CouponRecordDaoService couponRecordDaoService;
    
    @Value("#{settingConfig[ftp_eswp_ip]}")
    String bdFtpAddress;
    
    @Value("#{settingConfig[ftp_eswp_user]}")
    String bdFtpUsername;
    
    @Value("#{settingConfig[ftp_eswp_pwd]}")
    String bdFtpPwd;
    
    @Override
    public void deleteExpireValidActivity() {
        LOGGER.info("删除已过期鉴权过的活动列表定时任务开始----->");
        validActivityDaoService.deleteValidActivityBeforeDate(new Date());
        LOGGER.info("<-----删除已过期鉴权过的活动列表定时任务结束");
    }

    @Override
    public void sendCouponRecord2BigData(String startDateStr, String endDateStr) {
        Date startTime = null;
        Date endTime = null;
        if (StringUtils.isNotBlank(startDateStr)
                && StringUtils.isNotBlank(endDateStr)) {
            // 如果指定了日期区间，则取startDateStr 00:00:00~endDateStr 23:59:59
            startTime = DateUtils.getDateByStr(startDateStr + " 00:00:00", 
                    DateUtils.DEFAULT_TIME_PATTERN);
            endTime = DateUtils.getDateByStr(endDateStr + " 23:59:59", 
                    DateUtils.DEFAULT_TIME_PATTERN);
        } else {
            // 没有指定日期区间，默认取昨天的发券记录
            endTime = DateUtils.getNowZeroPoint();
            startTime = DateUtils.getNextDay(endTime, -1);
        }
        
        int totalSize = couponRecordDaoService.countCouponRecord(startTime, endTime);
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < totalSize; i += 500) {
            List<CouponRecord> list = couponRecordDaoService
                    .queryCouponRecords(startTime, endTime, i, 500);
            for (CouponRecord record : list) {
                builder.append(record.getOaAccountNo()).append(COLUMN_SPACE)
                    .append(record.getActivityId()).append(COLUMN_SPACE)
                    .append(record.getActivityName()).append(COLUMN_SPACE)
                    .append(DateUtils.getDateStrByFormat(record.getActStartTime(),
                            DateUtils.DEFAULY_FULL_TIME_PATTERN)).append(COLUMN_SPACE)
                    .append(DateUtils.getDateStrByFormat(record.getActEndTime(),
                            DateUtils.DEFAULY_FULL_TIME_PATTERN)).append(COLUMN_SPACE)
                    .append(record.getCouponId()).append(COLUMN_SPACE)
                    .append(record.getCouponNo()).append(COLUMN_SPACE)
                    .append(record.getCouponType()).append(COLUMN_SPACE)
                    .append(record.getCouponName()).append(COLUMN_SPACE)
                    .append(record.getCouponAmount()).append(COLUMN_SPACE)
                    .append(record.getCustNo()).append(COLUMN_SPACE)
                    .append(record.getTelNo()).append(COLUMN_SPACE)
                    .append(DateUtils.getDateStrByFormat(record.getSendTime(),
                            DateUtils.DEFAULY_FULL_TIME_PATTERN)).append(COLUMN_SPACE)
                    .append(record.getStoreCode()).append(COLUMN_SPACE)
                    .append(record.getStoreName()).append(COLUMN_SPACE)
                    .append(record.getRegionCode()).append(COLUMN_SPACE)
                    .append(record.getRegionName()).append(LINE_END)
                    .append(LINE_SPACE);
            }
        }
        try {
            if (StringUtils.isNotBlank(builder.toString())) {
                String dateStr = DateUtils.getDateStrByFormat(DateUtils.getNextDay(new Date(), -1)
                        , DateUtils.YYYYMMDD_PATTERN);
                FtpEntity ftpEntity = new FtpEntity(bdFtpAddress, bdFtpUsername, bdFtpPwd, dateStr);
                ByteArrayInputStream inputStream = new ByteArrayInputStream(
                        builder.toString().getBytes(Charsets.UTF_8));
                // 上传FLG文件
                FtpUtils.uploadFile(ftpEntity, "/A2089002_T_COUPON_RECORD_" + dateStr + ".FLG", new ByteArrayInputStream("".getBytes(Charsets.UTF_8)));
                // 上传DAT文件
                FtpUtils.uploadFile(ftpEntity, "/A2089002_T_COUPON_RECORD_" + dateStr + "_0001.DAT", inputStream);
            }
            
        } catch (Exception e) {
            LOGGER.error("upload file to bigdata ftp fail.", e);
        }
    }

}
